package com.yuan.admin.controller;

import com.yuan.admin.entity.UserEntity;
import com.yuan.admin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author SiYuan
 * @Description : 测试操作Mongo DB
 * @mail:15405258664@qq.com
 * @Date 2018/11/30 15:06
 */
@RestController
public class MongoController {
    @Autowired
    UserService userService;
    @Autowired
    MongoTemplate mongoTemplate;

    /***
     *  查询Mongo 的数据
     *
     * @return
     */
      @GetMapping("getuser")
      @ResponseBody
      public String  getUser(){
          String us = "siyuan";
          Query query = new Query(Criteria.where("userName").is(us));
          UserEntity user =  mongoTemplate.findOne(query , UserEntity.class);
          return user.toString();
      }
    /**
     * 插入数据
     *
     * @return
     */
    @GetMapping("mongo")
    @ResponseBody
    public String getMongo(){
        UserEntity userEntity = new UserEntity();
        userEntity.setId((long) 1111);
        userEntity.setPassWord("ssss");
        userEntity.setUserName("siyuan");
        mongoTemplate.save(userEntity);
        return "ok";
    }

    /***
     * 更新MongoDB 数据
     *
     * @return
     */
    @GetMapping("/updatauser")
    public String UpdataUser(){
        Query query=new Query(Criteria.where("id").is(1111));
        Update update= new Update().set("userName", "sy").set("passWord", "666");
        //更新查询返回结果集的第一条
        mongoTemplate.updateFirst(query,update,UserEntity.class);
        return "ok";
    }

    /***
     * 删除Mongo 用户
     * @return
     */
    @GetMapping("/deluser")
    @ResponseBody
    public String DelUser() {
        Query query=new Query(Criteria.where("id").is(1111));
        mongoTemplate.remove(query,UserEntity.class);
        return "删除用户";
    }

}
